package orm

import (
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type Option func(*gorm.DB) *gorm.DB

func SearchOption_UUID(uuid string) Option {
	return func(db *gorm.DB) *gorm.DB {
		db.Where("uuid = ?", uuid)
		return db
	}
}
func Option_Model(m schema.Tabler) Option {
	return func(db *gorm.DB) *gorm.DB {
		db.Model(m)
		return db
	}
}
func Option_Table(tableName string) Option {
	return func(db *gorm.DB) *gorm.DB {
		db.Table(tableName)
		return db
	}
}
func DoOption(db *gorm.DB, opts ...Option) *gorm.DB {
	db = db.Session(&gorm.Session{})
	for _, t := range opts {
		db = t(db)
	}
	return db
}
func GetFirstRecord(db *gorm.DB, in interface{}, options ...Option) error {
	db = DoOption(db, options...)
	return db.First(in).Error
}
func GetListRecord(db *gorm.DB, in interface{}, options ...Option) error {
	db = DoOption(db, options...)
	return db.Find(in).Error
}

func GetPageListRecord(db *gorm.DB, page, size int, in interface{}, options ...Option) (*BasePageResp, error) {
	data := &BasePageResp{
		Data: in,
	}
	db = DoOption(db, options...)
	db.Count(&data.Count)
	db.Limit(size).Offset((page - 1) * size)
	if err := GetListRecord(db, in); err != nil {
		return nil, err
	}
	return data, nil
}
